package model

import (
	"community_end/utils/errmsg"
	"gorm.io/gorm"
)

type Tag struct {
	gorm.Model
	Name       string `json:"name"`
	TopicCount int    `json:"topic_count"`
	Posts      []Post `gorm:"many2many:post_tag;"`
}

func (Tag) TableName() string {
	return "tag"
}

func SelectTagByName(name string) (Tag, int) {
	var tag Tag
	err := db.Where("name = ?", name).First(&tag).Error
	if err != nil || gorm.ErrRecordNotFound != nil {
		return Tag{}, errmsg.TAG_SELECT_FAILED
	}
	return tag, errmsg.SUCCESS
}

func InsertTag(tag Tag) (Tag, int) {
	err := db.Create(&tag).Error
	if err != nil {
		return Tag{}, errmsg.TAG_INSERT_FAILED
	}
	return tag, errmsg.SUCCESS
}
